package com.hht.netlibs

import android.util.Log
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.OkHttpClient
import okhttp3.Request
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.lang.Exception
import java.util.concurrent.TimeUnit
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

/**
 * Author:chen'hu
 * Time:2024/6/18 15:28
 * Description:This is NetWorkManagement
 */
object NetWorkManagement {
    private const val TIME_OUT = 30.toLong()
    private const val BASE_URL = "https://www.wanandroid.com/"
    private const val MOVIE_BASE_URL = "https://cdn.3dfan.3dv.cn/"

    private val okHttpClient: OkHttpClient = OkHttpClient.Builder()
        .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
        .readTimeout(TIME_OUT, TimeUnit.SECONDS)
        .writeTimeout(TIME_OUT, TimeUnit.SECONDS)
        .addInterceptor(LoggingInterceptor())
        .build()

    private val mRetrofit: Retrofit = Retrofit.Builder()
        .baseUrl(BASE_URL)
        .callFactory(object : ReplaceUrlCallFactory(okHttpClient) {
            override fun getNewUrl(baseUrlName: String, request: Request): HttpUrl? {
                if (baseUrlName == MOVIE_BASE_URL) {
                    val oldUrl = request.url.toString()
                    val newUrl = oldUrl.replace(BASE_URL, MOVIE_BASE_URL)
                    return newUrl.toHttpUrl()
                }
                return null
            }
        })
        .addConverterFactory(GsonConverterFactory.create())
        .build()

    inline fun <reified T> createServiceWithMySelf(): T {
        val serviceClass = T::class.java
        return createServiceApi(serviceClass)
    }

    fun <T> createServiceApi(tClass: Class<T>): T {
        return mRetrofit.create(tClass)
    }

    suspend fun <T> Call<T>.await(): T {
        return suspendCoroutine {
            enqueue(object : Callback<T> {
                override fun onResponse(call: Call<T>, response: Response<T>) {
                    response.body()?.let { body ->
                        it.resume(body)
                    }
                }

                override fun onFailure(call: Call<T>, t: Throwable) {
                    it.resumeWithException(t)
                }

            })
        }
    }
}